#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
一键启动完整MES系统 - 解决所有问题并启动
"""
import os
import sys
import subprocess
import time
import django
from django.core.management import execute_from_command_line

# 切换到项目目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(BASE_DIR)

def run_command_safe(cmd, capture=True):
    """安全运行命令"""
    try:
        if capture:
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True, cwd=BASE_DIR)
            return result.returncode == 0, result.stdout, result.stderr
        else:
            result = subprocess.run(cmd, shell=True, cwd=BASE_DIR)
            return result.returncode == 0, "", ""
    except Exception as e:
        return False, "", str(e)

def step_1_fix_imports():
    """步骤1: 批量修复导入问题"""
    print("=" * 60)
    print("步骤1: 批量修复Django导入问题")
    print("=" * 60)
    
    try:
        exec(open('batch_fix_imports.py').read())
        print("✓ 导入问题修复完成")
    except Exception as e:
        print(f"✗ 导入问题修复失败: {e}")

def step_2_setup_django():
    """步骤2: 设置Django环境"""
    print("\n" + "=" * 60)
    print("步骤2: 设置Django环境")
    print("=" * 60)
    
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings_mes_basic')
    
    try:
        import django
        print(f"✓ Django版本: {django.get_version()}")
        django.setup()
        print("✓ Django环境设置成功")
        return True
    except Exception as e:
        print(f"✗ Django环境设置失败: {e}")
        return False

def step_3_migrate_databases():
    """步骤3: 运行数据库迁移"""
    print("\n" + "=" * 60)
    print("步骤3: 运行数据库迁移")
    print("=" * 60)
    
    settings_list = [
        'settings_mes_basic',
        'settings_full_mes', 
        'settings_django_with_mes'
    ]
    
    for settings in settings_list:
        print(f"\n迁移 {settings}...")
        try:
            execute_from_command_line(['manage.py', 'migrate', f'--settings={settings}', '--run-syncdb'])
            print(f"✓ {settings} 迁移完成")
        except Exception as e:
            print(f"✗ {settings} 迁移失败: {e}")

def step_4_create_superuser():
    """步骤4: 创建超级用户"""
    print("\n" + "=" * 60)
    print("步骤4: 创建超级用户")
    print("=" * 60)
    
    try:
        from django.contrib.auth.models import User
        if not User.objects.filter(username='admin').exists():
            User.objects.create_superuser('admin', 'admin@example.com', 'admin123')
            print("✓ 超级用户创建成功")
        else:
            print("✓ 超级用户已存在")
    except Exception as e:
        print(f"✗ 超级用户创建失败: {e}")

def step_5_kill_existing_services():
    """步骤5: 清理现有服务"""
    print("\n" + "=" * 60)
    print("步骤5: 清理现有服务")
    print("=" * 60)
    
    print("清理现有MES服务进程...")
    success, _, _ = run_command_safe("pkill -f 'python manage.py runserver'", capture=False)
    time.sleep(2)
    print("✓ 现有服务已清理")

def step_6_start_services():
    """步骤6: 启动MES服务"""
    print("\n" + "=" * 60)
    print("步骤6: 启动MES服务")
    print("=" * 60)
    
    services = [
        {
            'name': '基础MES服务',
            'port': 8004,
            'settings': 'settings_mes_basic',
            'log': '/tmp/mes_8004.log'
        },
        {
            'name': '完整MES服务',
            'port': 8005,
            'settings': 'settings_full_mes',
            'log': '/tmp/mes_8005.log'
        },
        {
            'name': 'Django管理服务',
            'port': 8006,
            'settings': 'settings_django_with_mes',
            'log': '/tmp/mes_8006.log'
        }
    ]
    
    started_services = []
    
    for service in services:
        print(f"\n启动 {service['name']} (端口 {service['port']})...")
        cmd = f"python manage.py runserver 0.0.0.0:{service['port']} --settings={service['settings']}"
        
        try:
            # 使用subprocess.Popen启动后台服务
            process = subprocess.Popen(
                cmd.split(),
                stdout=open(service['log'], 'w'),
                stderr=open(service['log'], 'w'),
                cwd=BASE_DIR
            )
            started_services.append({
                'name': service['name'],
                'port': service['port'],
                'pid': process.pid,
                'log': service['log']
            })
            print(f"✓ {service['name']} 启动成功，PID: {process.pid}")
            time.sleep(2)  # 等待服务启动
        except Exception as e:
            print(f"✗ {service['name']} 启动失败: {e}")
    
    return started_services

def step_7_verify_services(started_services):
    """步骤7: 验证服务状态"""
    print("\n" + "=" * 60)
    print("步骤7: 验证服务状态")
    print("=" * 60)
    
    print("等待服务完全启动...")
    time.sleep(5)
    
    for service in started_services:
        print(f"\n检查 {service['name']} (PID: {service['pid']})...")
        success, stdout, stderr = run_command_safe(f"ps -p {service['pid']}")
        if success and str(service['pid']) in stdout:
            print(f"✓ {service['name']} 运行正常")
        else:
            print(f"✗ {service['name']} 可能启动失败，检查日志: {service['log']}")

def show_final_info(started_services):
    """显示最终信息"""
    print("\n" + "=" * 60)
    print("🎉 MES系统启动完成！")
    print("=" * 60)
    
    print("\n🌐 访问地址:")
    for service in started_services:
        if service['port'] == 8004:
            print(f"- {service['name']}: http://175.27.138.86:{service['port']}/admin/")
        elif service['port'] == 8005:
            print(f"- {service['name']}: http://175.27.138.86:{service['port']}/admin/")
        elif service['port'] == 8006:
            print(f"- {service['name']}: http://175.27.138.86:{service['port']}/admin/")
    
    print("\n🔑 登录信息:")
    print("- 用户名: admin")
    print("- 密码: admin123")
    
    print("\n📊 查看日志:")
    for service in started_services:
        print(f"- {service['name']}: tail -f {service['log']}")
    
    print("\n🛑 停止所有服务:")
    print("- pkill -f 'python manage.py runserver'")
    
    print("\n✅ 所有问题已解决，MES系统已完全启动！")

def main():
    """主函数"""
    print("🚀 一键启动完整MES系统")
    print(f"📁 工作目录: {os.getcwd()}")
    print(f"🕐 启动时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 执行所有步骤
    step_1_fix_imports()
    
    if not step_2_setup_django():
        print("❌ Django环境设置失败，退出")
        return
    
    step_3_migrate_databases()
    step_4_create_superuser()
    step_5_kill_existing_services()
    started_services = step_6_start_services()
    step_7_verify_services(started_services)
    show_final_info(started_services)

if __name__ == '__main__':
    main() 